<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Set数据结构</title>
</head>
<body>
    <h1>Set数据结构</h1>
    <h2>Set是一个不重复值的集合</h2>

    <script>
        // 基本用法
        const s = new Set();
        [2, 3, 5, 4, 5, 2, 2].forEach(x => s.add(x));
        console.log(s); // Set {2, 3, 5, 4}

        // Set的方法
        let set = new Set(['red', 'green', 'blue']);
        console.log(set.has('red')); // true
        set.delete('red');
        console.log(set.size); // 2
        set.clear();
        console.log(set.size); // 0

        // Set的遍历
        let set2 = new Set(['a', 'b', 'c']);
        set2.forEach((value, key) => console.log(value)); // a b c

        // Set转数组
        let arr = Array.from(set2);
        console.log(arr); // ['a', 'b', 'c']

        // 数组去重
        let array = [1, 1, 2, 3, 3, 4];
        let unique = [...new Set(array)];
        console.log(unique); // [1, 2, 3, 4]
    </script>
</body>
</html> 